const express = require('express')
const path = require('path')
const fs = require('fs')

const app = express()

/* 静态服务器 */
app.use(express.static(path.join(__dirname, 'public')))

/* 对请求体进行管理 */
app.use(express.json())

/* 启动服务 */
app.listen(8080, function() {
    console.log('*****************************************')
    console.log('* server start on http://localhost:8080 *')
    console.log('*****************************************')
})

/* 读取文件内容的方法 */
function getFileText(name) {
    return new Promise(resolve => {
        resolve(
            JSON.parse(fs.readFileSync(path.join(__dirname, 'mock', name)).toString())
        )
    })
}

/* 写入文件内容的方法 */
function writeFileText(name, data) {
    return new Promise(async resolve => {

        await fs.writeFileSync(path.join(__dirname, 'mock', name), JSON.stringify(data))

        resolve(true)
    })
}

/* 定义用户接口 */
app.put('/register', async function(req, res) {
    let body = req.body
    let userList = await getFileText('user.json')

    let msg = ''
    for (let it of userList) {
        if (it.id === body.id) {
            msg = '用户编码已经存在'
            break
        }
        if (it.phone === body.phone) {
            msg = '用户电话号码已经存在'
            break
        }
    }
    if (!!msg) {
        res.send({code: 400, message: msg})
        return
    }
    userList.push(body)

    /* 存储数据 */
    await writeFileText('user.json', userList)

    res.send({code: 200, message: '保存用户成功'})
})

/* 用户登录 */
app.post('/login', async function(req, res) {
    let {id, password} = req.body

    
    let userList = await getFileText('user.json')

    let obj = userList.find(it => it.id === id)
    
    if (!obj) {
        res.send({code: 400, message: '用户不存在'})
        return
    }

    if (obj.password !== password) {
        res.send({code: 400, message: '密码错误'})
        return
    }

    res.send({code: 200, message: '用户登录成功', data:obj})
})

/* 获取商品列表数据 */
app.get('/goods', async function(req, res) {
    let {page, size, id} = req.query
    let goodsList = await getFileText('goodsList.json')
    if (!!id) {
        goodsList = goodsList.filter(it => it.id.includes(id))
    }

    res.send({
        code: 200,
        data: {
            total: goodsList.length,
            rows: goodsList.slice((page - 1) * size, page * size)
        }
    })
})

// 获取单个商品信息
app.get('/goods/:id', async function(req,res) {
    let id= req.params.id
    let goodsList = await getFileText('goodsList.json')
    // if (!!id) {
    //     goodsList = goodsList.filter(it => it.id.includes(id))
    // }
    let obj = goodsList.find(it => it.id === id)

    if(!obj){
        res.send({code: '400', message: '用户不在'})
    }else{
        res.send({code: '200', message: '获取用户信息成功', data: obj})
    }  
})



/* 修改商品 */
app.post('/goods/:id', async function(req, res) {
    let data = req.body, id = req.params.id
    let goodsList = await getFileText('goodsList.json')
    let index = goodsList.findIndex(it => it.id === id)
    goodsList[index] = {...data, id}

    await writeFileText('goodsList.json', goodsList)

    res.send({code: '200', message: '修改成功',data:goodsList[index]})
})
// 删除商品信息
app.delete('/goods/:id', async function(req, res) {
    let id = req.params.id
    let goodsList = await getFileText('goodsList.json')
    let index = goodsList.findIndex(it => it.id === id)
    let obj = goodsList.find(it => it.id === id)
   
    
    goodsList.splice(index,1)
    await writeFileText('goodsList.json', goodsList)
    if(!obj){
        res.send({code: '400', message: '商品不在'})
    }else{
        res.send({code: '200', message: '删除成功'})
    }  
})

// 新建保存商品
app.put('/goods/save', async function(req, res) {
    let body = req.body
    let goodsList = await getFileText('goodsList.json')
    let msg = ''
    for (let it of goodsList) {
        if (it.id === body.id) {
            msg = '该商品已经存在'
            break
        }
        if (it.title === body.title) {
            msg = '该商品名已经存在'
            break
        }
    }
    if (!!msg) {
        res.send({code: 400, message: msg})
        return
    }
    goodsList.push(body)

    /* 存储数据 */
    await writeFileText('goodsList.json', goodsList)

    res.send({code: '200', message: '保存成功', data: body})
})


// 删除用户信息
app.delete('/user/:id',async function(req, res) {
    let id = req.params.id
    let userList = await getFileText('user.json')
    let obj = userList.find(it => it.id === id)
    let index = userList.findIndex(it => it.id === id)
    
    userList.splice(index,1)
    await writeFileText('user.json', userList)
    if(!obj){
        res.send({code: '400', message: '用户不在'})
    }else{
        res.send({code: '200', message: '删除成功', data: obj})
    }  
})


// 获取所有用户信息
app.get('/user/info/list', async function(req, res) {
    // console.log(req.query)
    let {page, size, name} = req.query
    let userList = await getFileText('user.json')

    if (!!name) {
        userList = userList.filter(it => it.name.includes(name))
    }
    res.send({code: '200', message: '获取用户信息成功', 

    data: {
        data: userList,
        total: userList.length,
        rows: userList.slice((page - 1) * size, page * size)
    }
})
})

// 获取单个用户信息
app.get('/user/:id', async function(req,res) {
    let id= req.params.id
    let userList = await getFileText('user.json')
    let obj = userList.find(it => it.id === id)

    if(!obj){
        res.send({code: '400', message: '用户不在'})
    }else{
        res.send({code: '200', message: '获取用户信息成功', data: obj})
    }  
})


// 修改用户信息

app.put('/user/:id', async function(req,res) {

    let data = req.body, id = req.params.id
    

    let userList = await getFileText('user.json')
    let obj = userList.find(it => it.id === id)
    let index = userList.findIndex(it => it.id === id)
    
    userList[index]={...data, id}
    await writeFileText('user.json', userList)
    if(!obj){
        res.send({code: '400', message: '用户不在'})
    }else{
        res.send({code: '200', message: '修改用户信息成功'})
    }  
})


// 新建用户
app.post('/user/save', async function(req, res) {
    let body = req.body
    let userList = await getFileText('user.json')
    let msg = ''
    for (let it of userList) {
        if (it.id === body.id) {
            msg = '用户编码已经存在'
            break
        }
        if (it.phone === body.phone) {
            msg = '用户电话号码已经存在'
            break
        }
    }
    if (!!msg) {
        res.send({code: 400, message: msg})
        return
    }
    userList.push(body)

    /* 存储数据 */
    await writeFileText('user.json', userList)

    res.send({code: '200', message: '保存成功', data: body})
})



// 新建客户
app.put('/customer/save', async function(req, res) {
    let body = req.body
    let customerList = await getFileText('customer.json')
    let msg = ''
    for (let it of customerList) {
        if (it.id === body.id) {
            msg = '客户名称已经存在'
            break
        }
    }
    if (!!msg) {
        res.send({code: 400, message: msg})
        return
    }
   
    customerList.push(body)

    /* 存储数据 */
    await writeFileText('customer.json', customerList)

    res.send({code: '200', message: '保存成功', data: body})
})



// 删除客户信息
app.delete('/customer/:id',async function(req, res) {
    let id = req.params.id
    let customerList = await getFileText('customer.json')
    let obj = customerList.find(it => it.id === id)
    let index =customerList.findIndex(it => it.id === id)
    
    customerList.splice(index,1)
    await writeFileText('customer.json', customerList)
    if(!obj){
        res.send({code: '400', message: '客户不在'})
    }else{
        res.send({code: '200', message: '删除成功', data: obj})
    }  
})

app.get('/customer/info/lists',async function(req, res) {
    let customerList = await getFileText('customer.json')
    
    res.send({code: '200', message: '获取用户信息成功', 
    data:{
        data:customerList,
        total: customerList.length,
        }
    })

})

// 获取所有客户信息
app.get('/customer/info/list', async function(req, res) {
    // console.log(req.query)
    let {page, size, id, industry, type, date} = req.query
    let customerList = await getFileText('customer.json')

    if (!!id) {
        customerList = customerList.filter(it => it.id.includes(id))
    }
    if (!!industry) {
        customerList = customerList.filter(it => it.industry.includes(industry))
    }
    if (!!type) {
        customerList = customerList.filter(it => it.type.includes(type))
    }
    if (!!date) {
        customerList = customerList.filter(it => it.date.includes(date))
    }
    res.send({code: '200', message: '获取用户信息成功', 

    data: {
        data: customerList,
        total: customerList.length,
        rows: customerList.slice((page - 1) * size, page * size)
    }
})
})

// 获取单个客户信息
app.get('/customer/:id', async function(req,res) {
    let id= req.params.id
    let customerList = await getFileText('customer.json')
    let obj = customerList.find(it => it.id === id)

    if(!obj){
        res.send({code: '400', message: '客户不在'})
    }else{
        res.send({code: '200', message: '获取课户信息成功', data: obj})
    }  
})


// 修改客户信息

app.put('/customer/:id', async function(req,res) {

    let data = req.body, id = req.params.id
    

    let customerList = await getFileText('customer.json')
    let obj = customerList.find(it => it.id === id)
    let index = customerList.findIndex(it => it.id === id)
    
    customerList[index]={...data}
    await writeFileText('customer.json', customerList)
    if(!obj){
        res.send({code: '400', message: '修改失败，无该客户'})
    }else{
        res.send({code: '200', message: '修改用户信息成功'})
    }  
})




// 获取、查询所有人销售信息
app.get('/sale/info/list', async function(req, res) {
    res.send({
        code: 200,
        data: [
            {
                "id": "李天一",
                "number": Math.ceil(Math.random() * 100 + 10)
          },{
                "id": "王小明",
                "number": Math.ceil(Math.random() * 100 + 30)
          },{
                "id": "徐璐",
                "number": Math.ceil(Math.random() * 100 + 50)
          },{
                "id": "赵望望",
                "number": Math.ceil(Math.random() * 100 + 20)
          },{
                "id": "徐天",
                "number": Math.ceil(Math.random() * 100 + 30)
          },{
                "id": "王一鸣",
                "number": Math.ceil(Math.random() * 100 + 60)
          },{
                "id": "地方",
                "number": Math.ceil(Math.random() * 100 + 70)
          },{
                "id": "的话",
                "number": Math.ceil(Math.random() * 100 + 30)
          },{
                "id": "贷款",
                "number": Math.ceil(Math.random() * 100 + 20)
          },{
                "id": "大家",
                "number": Math.ceil(Math.random() * 100 + 0)
          }
        ]
    })
})


// 获取、查询所有人销售数据分析
app.get('/saledata/info/list', async function(req, res) {
    res.send({
        code: 200,
        data: [
            { 
                  "value": Math.ceil(Math.random() * 200 + 900), 
                  "name": "合同签订" 
            },{
                  "value": Math.ceil(Math.random() * 200 + 100), 
                  "name": "方案展示" 
            },{ 
                  "value": Math.ceil(Math.random() * 200 + 400), 
                  "name": "合同谈判" 
            },{ 
                  "value": Math.ceil(Math.random() * 200 + 100), 
                  "name": "首次拜访" 
            },{ 
                  "value": Math.ceil(Math.random() * 200 + 300), 
                  "name": "产品报价" 
            },{ 
                  "value": Math.ceil(Math.random() * 200 + 200), 
                  "name": "需求获取" 
            }
        ]
    })
})



// 获取、查询所有人销售信息
app.get('/sale/info/list', async function(req, res) {
    res.send({
        code: 200,
        data: [
            {
                "id": "李天一",
                "number": Math.ceil(Math.random() * 100 + 10)
          },{
                "id": "王小明",
                "number": Math.ceil(Math.random() * 100 + 30)
          },{
                "id": "徐璐",
                "number": Math.ceil(Math.random() * 100 + 50)
          },{
                "id": "赵望望",
                "number": Math.ceil(Math.random() * 100 + 20)
          },{
                "id": "徐天",
                "number": Math.ceil(Math.random() * 100 + 30)
          },{
                "id": "王一鸣",
                "number": Math.ceil(Math.random() * 100 + 60)
          },{
                "id": "地方",
                "number": Math.ceil(Math.random() * 100 + 70)
          },{
                "id": "的话",
                "number": Math.ceil(Math.random() * 100 + 30)
          },{
                "id": "贷款",
                "number": Math.ceil(Math.random() * 100 + 20)
          },{
                "id": "大家",
                "number": Math.ceil(Math.random() * 100 + 0)
          }
        ]
    })
})




